package projetomsn.Client.UI;

import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import projetomsn.Client.ServerInterface.ClientManager;
import projetomsn.Client.UI.FontConfig.FontHTML;
import projetomsn.Server.ServerSettings;


/**
 * Classe da janela principal de conversação
 * @author HUMBERTO RAMOS
 */
public class SingleChatFrame extends javax.swing.JFrame{

    /**
     * Atributo de nome do usuário
     */
    public String userName = "";
    
    private ClientManager clientManager;
    /**
     * Atributo de nome do amigo
     */
    public String friendName;
    /**
     * Variavel que mostra se a janela de conversação está visivel
     */
    public boolean isVisible=false;
   
    /**
     * Parte inicial do HTML
     */
    private String HEADER ;
     /**
     * Parte final do HTML
     */
    private String BODY;
    /**
     * Atributo de mensagem a ser recebida
     */
    private StringBuilder messageSentReceived;
    /**
     * Atributo de mensagem a ser enviada
     */
    private StringBuilder messageToSend;
    /**
     * Atributo de fonte do nome do usuário
     */
    //used for text style
    private FontHTML myNameFont;
    /**
     * Atributo de fonte do separador, nome da mensagem, do usuário
     */
    private FontHTML mySeparatorFont;
    /**
     * Atributo de fonte da mensagem do usuário
     */
    private FontHTML myTextFont;
    /**
     * Atributo de fonte do nome do amigo
     */
    private FontHTML friendNameFont;
    /**
     * Atributo de fonte do separado, nome da mensagem, do amigo
     */
    private FontHTML friendSeparatorFont;
    /**
     * Atributo de fonte da mensagem do amigo
     */
    private FontHTML friendTextFont;
    /**
     * Lista de emoticons
     */
    private ArrayList<String> emoticonsCode;//used to record emoticons code
    /**
     * Numero de caracteres permitidos na mensagem
     */
    int characterRemaining = 150;
    /**
     * Boolean de inserção de emoticons
     */
    private boolean canInsertEmoticons = true;
    /**
     * Cria uma nova janela de chat
     */
    public SingleChatFrame(ClientManager manager,String friendName,String userName) {
        super("FRIEND: "+friendName);
        initComponents();
        clientManager = manager;
        setFriendName(friendName);
        this.userName=userName;
        initVar();
       

    }
    private void initVar(){
        HEADER = ""
            + "<html>"
            + "<body>";
        BODY = ""
            + "</body>"
            + "</html>";
        displayMessageTextPane.setContentType("text/html");
       
    }
    /**
     * This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
   

    /**
     * Evento gerado botão de envio de mensagem
     * @param evt 
     */
    private void sendMessageButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendMessageButtonActionPerformed
        // TODO add your handling code here:
        
      clientManager.send(friendName+ServerSettings.marca
              +userName,
               inputMessageTextPane.getText()); // send message
       
       inputMessageTextPane.setText(""); // clear inputArea

    }//GEN-LAST:event_sendMessageButtonActionPerformed

    /**
     * mosta as mensagens eviadas e recebidas
     * @param message 
     */
    private void displayMessage(String message) {
      //   messageSentReceived = messageSentReceived.append("<br>"
        //        + message);
       displayMessageTextPane.setText("\n" +HEADER+ message+BODY);
    }

    private String getTextWithFontSet(String text) {
        try {
            StringTokenizer msgReceived = new StringTokenizer(text,ServerSettings.marca);
            String name, separator, msg;
            name = msgReceived.nextToken();
            separator = msgReceived.nextToken();
            msg = msgReceived.nextToken();



            msg = Emoticon.addEmoticonsToMessageReceived(msg);//add emoticons to message

            if (userName.equals(name)) {
                return myNameFont.setFont(name,
                        myNameFont.color,
                        myNameFont.STYLE,
                        myNameFont.size,
                        myNameFont.BOLD,
                        myNameFont.ITALIC,
                        myNameFont.UNDERLINE)
                        + mySeparatorFont.setFont(separator,
                        mySeparatorFont.color,
                        mySeparatorFont.STYLE,
                        mySeparatorFont.size,
                        mySeparatorFont.BOLD,
                        mySeparatorFont.ITALIC,
                        mySeparatorFont.UNDERLINE)
                        + myTextFont.setFont(msg,
                        myTextFont.color,
                        myTextFont.STYLE,
                        myTextFont.size,
                        myTextFont.BOLD,
                        myTextFont.ITALIC,
                        myTextFont.UNDERLINE);
            } else {
                return friendNameFont.setFont(name,
                        friendNameFont.color,
                        friendNameFont.STYLE,
                        friendNameFont.size,
                        friendNameFont.BOLD,
                        friendNameFont.ITALIC,
                        friendNameFont.UNDERLINE)
                        + friendSeparatorFont.setFont(
                        separator,
                        friendSeparatorFont.color,
                        friendSeparatorFont.STYLE,
                        friendSeparatorFont.size,
                        friendSeparatorFont.BOLD,
                        friendSeparatorFont.ITALIC,
                        friendSeparatorFont.UNDERLINE)
                        + friendTextFont.setFont(msg,
                        friendTextFont.color,
                        friendTextFont.STYLE,
                        friendTextFont.size,
                        friendTextFont.BOLD,
                        friendTextFont.ITALIC,
                        friendTextFont.UNDERLINE);
            }
        } catch (NoSuchElementException exeception) {
            return "";
        }
    }
    /**
     * Metodo para pegar a mensagem
     * @param message 
     */
    public synchronized  void getMessage(String message) {
        displayMessage(message);
    }
    
    
    /**
     * Metodo para atribuir o nome do amigo
     * @param args the command line arguments
     */
    public void setFriendName(String name){
        friendName=name;
    }
    /**
     * Retorna o nome do usuário
     * @return 
     */
    public String getUserName() {
        return userName;
    }
    // Variables declaration - do not modify                     
   
    // End of variables declaration                   
   
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        displayMessageTextPane = new javax.swing.JTextPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        inputMessageTextPane = new javax.swing.JTextPane();
        sendMessageButton = new javax.swing.JButton();
        emoticonButton = new javax.swing.JButton();
        fontStyleButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        mainPanel.setBackground(new java.awt.Color(234, 225, 242));
        mainPanel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, null, new java.awt.Color(153, 0, 153), null, null));

        displayMessageTextPane.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(213, 170, 246), 2, true));
        displayMessageTextPane.setEditable(false);
        jScrollPane1.setViewportView(displayMessageTextPane);

        inputMessageTextPane.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(225, 194, 250), 2, true));
        jScrollPane2.setViewportView(inputMessageTextPane);

        sendMessageButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/botoes_icones/sendMessage.png"))); // NOI18N
        sendMessageButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendMessageButtonActionPerformed(evt);
            }
        });

        emoticonButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/Emoticons/emotion_menu.gif"))); // NOI18N

        fontStyleButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/Font/style_1.png"))); // NOI18N
        fontStyleButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fontStyleButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 477, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 477, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(sendMessageButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(fontStyleButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(emoticonButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                        .addComponent(fontStyleButton)
                        .addGap(40, 40, 40)
                        .addComponent(emoticonButton, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(sendMessageButton)
                        .addGap(35, 35, 35))))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void fontStyleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fontStyleButtonActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_fontStyleButtonActionPerformed

    private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
  
    /**
     * Inicializa componentes criados pelo netbeans
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextPane displayMessageTextPane;
    private javax.swing.JButton emoticonButton;
    private javax.swing.JButton fontStyleButton;
    private javax.swing.JTextPane inputMessageTextPane;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JButton sendMessageButton;
    // End of variables declaration//GEN-END:variables
}
